package cn.com.infcn.spider.io.output.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.alibaba.fastjson.JSONObject;

import cn.com.infcn.spider.domain.Doc;
import cn.com.infcn.spider.io.output.Output;

public class fileOutput implements Output {

	private OutputStream os = null;

	private byte[] LINE = "\n".getBytes();
	
	private String charEncoding = "utf-8";
	private boolean append = false ;

	public fileOutput(JSONObject job, String jobName) {
		String path = job.getString("path");
		if (job.containsKey("charEncoding")) {
			charEncoding = job.getString("charEncoding");
		}
		
		if(job.containsKey("append")){
			append = job.getBooleanValue("append") ;
		}
		
		try {
			os = new FileOutputStream(new File(path), append);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void save(Doc doc) throws Exception {
		os.write(doc.getResult().toString().getBytes());
		os.write(LINE);
	}

	@Override
	public void flush() throws IOException {
		os.flush();
	}

	@Override
	public void shutdown() throws IOException {
		flush();
		os.close();
	}

}
